package com.Hsu.book.controller;

import com.Hsu.book.constant.Constants;
import com.Hsu.book.model.UserInfo;
import com.Hsu.book.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @author Hsu琛君珩
 * @ClassName:UserController
 * @date 2024-01-04
 * @apiNote
 * @Version: v1.0
 */

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Boolean login(String userName, String password, HttpSession session) {
        //校验参数
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return false;
        }

        //1.根据用户名去查找用户信息
        UserInfo userInfo = userService.getUserInfoByName(userName);
        if(userInfo==null||userInfo.getId()<0){
            return false;
        }
        //2.比对密码是否正确
        //验证账号密码是否正确
        //if(userName.equals("admin")这种写法，如果userName为null就会报空指针异常
        //这是开发习惯，要养成
        if(password.equals(userInfo.getPassword())){
            //密码正确
            //存session
            userInfo.setPassword("");
            session.setAttribute(Constants.SESSION_USER_KEY, userInfo);
            return true;
        }
        return false;
    }
}
